package com.mbschenkel.client;

import java.io.Serializable;

import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;

public class SessionData implements Serializable {
	public static final class SessionVerificationData implements Serializable {
		public int sessionID = -1;
		public String sessionSecret = "";
	}
	// enum is not serializable....
	/*public enum TrustLevel { 
		tlNone (0),
		tlRead (1),
		tlWhitelist (3),
		tlNormal(5),
		tlBlacklist(7),
		tlAll(20),
		tlAdmin(100);
	    private final int level;   
    	TrustLevel(int level) {
    		this.level = level;
    	}
    	public int getValue() { return level; }
	}; */
	public int userID;
	public int sessionID;
	public String userName;
	public String loginRequestName;
	public String loginRequestPasswordHash; // used from client to server only!!!
	public String sessionSecret;
	public String emailAddress;
	//public TrustLevel trustLevel = TrustLevel.tlRead;
	public int trustLevel;
	
	//public SessionData() {}
	
	/**
	 * reset all values used by c'tor and for logout funcitonality
	 */
	public void clear() {
		 userID = -1;
		 sessionID = -1;
		 userName = "anonymous";
		 loginRequestName = "";
		 loginRequestPasswordHash = "";
		 sessionSecret = "";
		 emailAddress = "";
		 trustLevel = 0;
	}
	/**
	 * c'tor uses clear();
	 */
	public SessionData() {
		clear();
	}
	/**
	 * handels login, default session creation, re-visits, logouts
	 */
	public void syncRemotely() {
		AsyncCallback<SessionData> callBackHandler = new AsyncCallback<SessionData>(){
			public void onFailure(Throwable caught) {
				GWT.log("Session sync failed",caught);
			};
			public void onSuccess(SessionData result) {
				GWT.log("Session sync onSucces",null);
				if( result == null ){
					Window.alert("Session sync error");
					// unknown user or logout or ???
				} else {
					userID = result.userID;
					sessionID = result.sessionID;
					userName = result.userName;
					loginRequestName = "";
					loginRequestPasswordHash = "";
					sessionSecret = result.sessionSecret;
					emailAddress = result.emailAddress;
					trustLevel = result.trustLevel;
				}
				Session.getInstance().updateSessionPanel();
			};
		};
		Session.getInstance().latexService.syncSession( this, callBackHandler );
	}
	/**
	 * 
	 */
	public SessionVerificationData getSessionVerificationData() {
		SessionVerificationData result = new SessionVerificationData();
		result.sessionID = sessionID;
		result.sessionSecret = sessionSecret;
		return result;
	}
}

